import java.util.StringTokenizer;
import java.util.Stack;

public class MyDC {
    String q;
    Stack stack;

    public MyDC() {
        stack = new Stack();
    }

    void set(String question) {   //输入后续排列的字符串
        q = question;
    }


    public Rational get() {
        Rational op1 = new Rational();
        Rational op2 = new Rational();
        Rational result = new Rational();
        result.setNumerator(0);
        StringTokenizer token = new StringTokenizer(q, " ");
        String temp;
        while (token.hasMoreTokens()) {
            temp = token.nextToken();
            if (Isop(temp) == 1)//遇到操作符，弹出栈顶的两个数进行运算
            {
                op2 = (Rational) stack.pop();
                op1 = (Rational) stack.pop();//弹出最上面两个操作数
                result = cal(temp.charAt(0), op1, op2);//根据运算符进行运算
                stack.push(result);//将计算结果压栈
            } else {
                Rational num = new Rational();
                num.setNumerator(Integer.parseInt(temp));
                stack.push(num);//操作数入栈
            }
        }
        return result;
    }

    Rational cal(char op, Rational a, Rational b) {           //对栈顶弹出的两个数进行运算
        Rational c = new Rational();
        switch (op) {
            case '+':
                c = a.add(b);
                break;
            case '-':
                c = a.sub(b);
                break;
            case '*':
                c = a.muti(b);
                break;
            case '÷':
            case '/':
                if(b.getNumerator()==0) {
                    System.out.println("生成的算式计算时出现了分母为0的情况！");
                    System.exit(0);
                }
                else {
                    c = a.div(b);
                    break;
                }
            default:
                System.out.println("Wrong!");
        }
        return c;
    }

    int Isop(String op) {       //判断是不是运算符
        if (op.equals("+") || op.equals("-") || op.equals("*") || op.equals("÷") || op.equals("/")) {
            return 1;
        } else {
            return 0;
        }
    }
}





